package com.gmom.tako;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.gmom.tako.db.DbAccessor;
import com.gmom.tako.model.Rss;
import com.gmom.tako.model.Url;
import com.gmom.tako.network.RssGetter;

public class RssReaderTask extends AsyncTask<Url, Void, List<Rss>>{
	public static List<Rss> getRss(Context context, Url url){
		RssGetter getter = RssGetter.getInstance();
		DbAccessor db = new DbAccessor();
		
		//url_id = 1;
		//String rssUrl = (String)db.getUrl(url.get_id()).getUrl();
		
		// URL 登録するとき
		/*
		Url url = new Url();
		url.setTitle("gesote");
		url.setUrl("http://yaplog.jp/lp-yuji/index1_0.rdf");
		db.insertUrl(context, url); 
		*/
		
		List<Rss> rss = getter.parse(url.getUrl());
		if (rss == null) {
			rss = db.getRssList(context, url.get_id()); // 1 っていうのはURLリストビューで押されたポジションのIDを渡す
			if (rss == null) rss = new ArrayList<Rss>();
		} else {
			for (Rss entry : rss) {
				entry.setUrl_id(url.get_id());
			}
			db.insertRssList(context, rss);
		}
		return rss;
	}

	private AsyncTaskProgress progress;
	private Context context;
	public RssReaderTask(AsyncTaskProgress progress, Context context) {
		this.progress = progress;
		this.context = context;
	}
	@Override
	protected List<Rss> doInBackground(Url... params) {
		ArrayList<Rss> rss = new ArrayList<Rss>();
		for (Url url : params) {
			rss.addAll(getRss(this.context, url));
		}
		return rss;
	}
	
	@Override
	protected void onPostExecute(List<Rss> result) {
		progress.onComplete(result);
	}
}
